<template>
  <div>
    <div v-if="props.data.length > 0">
      <div class="custom-legend" :class="{ collapsed: !showAll }">
        <div class="grid grid-cols-3">
          <template v-for="item in cp_legendList" :key="item.legendName">
            <van-popover v-model:show="showPopover" theme="dark">
              <span class="flex flex-row w-[150px] p-1 text-xs">
                <div
                  class="legend-dot mt-1 ml-1"
                  :style="{
                    background: item.color,
                    width: '10px !important',
                    height: '10px !important',
                    borderRadius: '50% !important',
                    display: 'inline-block !important',
                    marginRight: '6px !important',
                    flexShrink: 0,
                  }"
                ></div>
                <div class="flex-1 min-w-0">
                  {{ item.name }}
                </div>
              </span>
              <template #reference>
                <div class="legend-item" :style="{ color: '#595959' }">
                  <div class="legend-dot" :style="{ background: item.color }"></div>
                  {{ item.legendName }}
                </div>
              </template>
            </van-popover>
          </template>
        </div>

        <div
          v-if="needExpand"
          class="flex flex-row gap-[2px] items-center justify-center w-full text-yxt-blue text-sm"
          @click="showAll = !showAll"
        >
          {{ showAll ? "收起" : "展开" }}
          <van-icon :name="showAll ? 'arrow-up' : 'arrow-down'" size="12"></van-icon>
        </div>
      </div>
      <p class="text-[#BFBFBF] text-xs mt-2 ml-8">点击象限名称可查看详情</p>
      <div ref="chartRef" style="width: 100%; height: 340px"></div>
    </div>
    <ChartEmpty class="p-6" v-else />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount, defineProps, computed } from "vue";
import * as echarts from "echarts";
import ChartEmpty from "@/components/charts/chartEmpty.vue";


export interface ScatterChartData {
  name: string;
  legendName: string;
  dataList: Array<[]>;
  color: string;
}

const props = defineProps({
  data: {
    type: Array<ScatterChartData>,
    required: true,
    default: []
  },
  passValueX: {
    type: Number,
    default: 80
  },
  passValueY: {
    type: Number,
    default: 80
  }
});
const chartRef = ref(null);
let chartInstance : echarts.EChartsType;

// 计算所有数据中的x/y最小值
const allData : [][] = props.data.flatMap(
  (item: ScatterChartData) => item.dataList
);

const originMinX = Math.floor(Math.min(props.passValueX, (allData.length ? Math.min(...allData.map(({value}) => value[0])) : 60)) / 10) * 10;
const originMinY = Math.floor(Math.min(props.passValueY, (allData.length ? Math.min(...allData.map(({value}) => value[1])) : 60)) / 10) * 10;
const originMaxX = 100;
const originMaxY = 100;

let xMin : number = originMinX;
let yMin : number = originMinY;
let xMax : number = originMaxX;
let yMax : number = originMaxY;


const xPass = props.passValueX;
const yPass = props.passValueY;

const maxNum = 9;

const cp_legendList = computed(() => {
  return showAll.value ? props.data : props.data.slice(0,maxNum);
});

const showAll = ref(false);
const needExpand = computed(() => {
  return props.data.length >= 8;
});

const series = props.data.map(({name,dataList,color }) => ({
  name: name,
  type: "scatter",
  encode: { tooltip: [0, 1] },
  data: dataList,
  symbolSize: 10,
  color,
  markLine: {
    symbol: "none",
    silent: false,
    lineStyle: {
      type: "dashed",
      color: "#04CCA4"
    },
    data: [
      { xAxis: xPass }, // x轴中间线
      { yAxis: yPass }  // y轴中间线
    ],
    label: {
      show: true,
      position: "start",
      color: "#04CCA4",
      formatter: function() {
        return "标值";
      }
    }
  }
}));

console.log("series: ", series);

const gridTop = 40;
const gridBottom = 40;
const gridLeft = 40;
const gridRight = 20;

onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  chartInstance && chartInstance.dispose();
});

function initChart() {
  if (!chartRef.value) {
    return;
  }
  if (chartInstance) {
    return;
  }
  chartInstance = echarts.init(chartRef.value);

  // 监听鼠标事件，当鼠标在 graphic 元素上时隐藏 tooltip
  chartInstance.on("mouseover", function(params : any) {
    if (params.componentType === "graphic") {
      chartInstance.dispatchAction({
        type: "hideTip"
      });
    }
  });

  // 监听 tooltip 显示事件，如果是 graphic 元素则不显示
  chartInstance.on("showTip", function(params : any) {
    if (params.componentType === "graphic") {
      chartInstance.dispatchAction({
        type: "hideTip"
      });
    }
  });

  // 监听鼠标进入事件，如果是 graphic 元素则阻止 tooltip 显示
  chartInstance.on("mouseover", function(params : any) {
    if (params.componentType === "graphic") {
      // 立即隐藏 tooltip
      chartInstance.dispatchAction({
        type: "hideTip"
      });
      // 阻止后续的 tooltip 显示
      return false;
    }
  });

  updateChart();
}

function updateChart() {
  if (!chartInstance) {
    return;
  }
  const option = {
    grid: {
      left: gridLeft,
      right: gridRight,
      top: gridTop,
      bottom: gridBottom
    },
    // 不需要 toolbox
    tooltip: {
      position: "top",
      trigger: "item",
      triggerOn: "mousemove",
      showContent: function(params : any) {
        // 如果是 graphic 元素，不显示 tooltip 内容
        return params.componentType !== "graphic";
      },
      formatter: function(params : any) {
        console.log("chart formatter: ", params);
        const { seriesName, data, componentType, value : chartValue } = params;

        if (componentType === "markLine") {
          return `达标:${chartValue}`;
        }

        const { name, value } = data;
        return `${name}<br/><br/>${seriesName}<br/><br/>能力评分: ${value[0]?.toFixed(1)}分<br/>任务达成: ${value[1]?.toFixed(1)}%`;
      },
      backgroundColor: "rgba(0,0,0,0.8)",
      borderColor: "transparent",
      textStyle: {
        color: "#fff",
        fontSize: 12
      },
      extraCssText: "max-width: 120px; word-wrap: break-word; white-space: normal; overflow: visible;"
    },
    xAxis: {
      min: xMin,
      max: xMax,
      splitNumber: 4,
      interval: 10,
      axisTick: {
        show: false // 隐藏x轴刻度线
      },
      axisLabel: {
        fontSize: 13,
        formatter: function (value : number) {
          if (value === xPass) return "";
          return value;
        },
        rich: {
          green: {
            color: "#04CCA4"
          }
        },
        color: "#999"
      },

      splitLine: {
        show: true,
        ineStyle: {
          type: "dashed",
          color: "#E9E9E9"
        }
      }
    },
    yAxis: {
      min: yMin,
      max: yMax,
      splitNumber: 4,
      interval: 10,
      axisTick: {
        show: false // 隐藏x轴刻度线
      },
      axisLabel: {
        fontSize: 13,
        formatter: function (value: number) {
          if (value === yPass) return "";
          return value;
        },
        rich: {
          green: {
            color: "#04CCA4"
          }
        },
        color: "#999"
      },
      name: "任务达成(%)",
      nameTextStyle: {
        color: "#595959",
        fontSize: 12,
        align: "left",
        padding: [0, 0, 0, 0]
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: "dashed",
          color: "#E9E9E9"
        }
      }
    },
    legend: { show: false },
    series: series,
    graphic: [
      {
        type: "text",
        right: gridRight - 10,
        bottom: -1,
        style: {
          text: "能力评估(分)",
          fill: "#595959",
          font: "13px"
        },
        silent: true // 禁用交互，避免tooltip
      },
      {
        type: "text",
        right: quadrantType.value === 0 ? 1000 : gridRight,
        top: 10,
        style: {
          text: "重置",
          fill: "#436bff",
          font: "12px sans-serif",
          cursor: "pointer"
        },
        silent: false, // 允许响应事件
        onclick: () => {
          onClickSubQuadrant(originMinX,originMinY,originMaxX, originMaxY,0);
        }
      },
      // 象限标签
       {
        type: "text",
        left: 50,
        top: gridTop + ((quadrantType.value === 1 || quadrantType.value === 0) ? 10 : 1000),
        style: {
          text: "工蜂型销售",
          fill: "#436bff",
          font: "12px sans-serif",
          cursor: "pointer"
        },
        silent: false, // 允许响应事件
        onclick: () => {
          onClickSubQuadrant(originMinX,yPass,xPass, originMaxY,1);
        }
      },
       {
        type: "text",
        right: gridRight + ((quadrantType.value === 2 || quadrantType.value === 0) ? 5 : 1000),
        top: gridTop + 10,
        style: {
          text: "明星型销售",
          fill: "#436bff",
          font: "12px sans-serif",
          cursor: "pointer"
        },
        silent: false, // 允许响应事件
        onclick: () => {
          onClickSubQuadrant(xPass,yPass,originMaxX, originMaxY,2);
        }
      } ,
      {
        type: "text",
        left: ((quadrantType.value === 3 || quadrantType.value === 0) ? 50 : 1000),
        bottom: 48,
        style: {
          text: "双困型销售",
          fill: "#436bff",
          font: "12px sans-serif",
          cursor: "pointer"
        },
        silent: false, // 允许响应事件
        onclick: () => {
          onClickSubQuadrant(originMinX,originMinY,xPass, yPass,3);
        }
      } ,
      {
        type: "text",
        right: gridRight + ((quadrantType.value === 4 || quadrantType.value === 0) ? 5 : 1000),
        bottom: 48,
        style: {
          text: "孤狼型销售",
          fill: "#436bff",
          font: "12px sans-serif",
          cursor: "pointer"
        },
        silent: false, // 允许响应事件
        onclick: () => {
          onClickSubQuadrant(xPass,originMinY,originMaxX, yPass,4);
        }
      }
    ]
  };

  chartInstance.setOption(option);
}

// type 0 1 2 3 4
const quadrantType = ref(0);
//点击子象限
function onClickSubQuadrant(tminX : number, tminY : number, tmaxX : number, tmaxY : number, type : number) {
   xMin = tminX;
   yMin = tminY;
   xMax = tmaxX;
   yMax = tmaxY;
   quadrantType.value = type;
   updateChart();
}

// 监听数据变化
watch(
  () => props.data,
  () => {
    updateChart();
  },
  { deep: true }
);
</script>

<style scoped>
.custom-legend {
  transition: height 0.2s;
  height: auto;
  background: white;
  padding: 8px 24px 8px 24px;
}

.legend-list {
  display: flex;
  flex-wrap: wrap; /* 允许自动换行 */
  gap: 12px 12px; /* 行间距、列间距可自定义 */
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  margin-bottom: 4px;
  min-width: 80px;
}

.legend-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  display: inline-block;
  margin-right: 6px;
}
</style>
